package com.atguigu.eud_teacher.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eud_teacher.dao.SubjectDao;
import com.atguigu.eud_teacher.entity.SubjectEntity;
import com.atguigu.eud_teacher.entity.excle.SubjectData;
import com.atguigu.eud_teacher.listener.SubjectExecleListener;
import com.atguigu.eud_teacher.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectDao, SubjectEntity> implements SubjectService {

    public void batchImport(MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExecleListener(baseMapper)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    //获取一二级联动
    public List<SubjectEntity> getSujectList() {
        //获取一级分类
        List<SubjectEntity> objList = baseMapper.selectList(null);
        List<SubjectEntity> finalList = new ArrayList<>();
        for (SubjectEntity oneSubjectEntity : objList) {
            if (oneSubjectEntity.getParentId().equals("0")) {
                finalList.add(selectTwoSubjectList(oneSubjectEntity, objList));
            }
        }
        return finalList;
    }

    private SubjectEntity selectTwoSubjectList(SubjectEntity oneSubjectEntity, List<SubjectEntity> objList) {
        oneSubjectEntity.setChildren(new ArrayList<>());
        for (SubjectEntity twoSubjectEntity : objList) {
            if (oneSubjectEntity.getId().equals(twoSubjectEntity.getParentId())) {
                oneSubjectEntity.getChildren().add(selectTwoSubjectList(twoSubjectEntity, objList));
            }
        }
        return oneSubjectEntity;
    }
}

